﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using FmcWebsite.Core;

namespace ContentManagementAdministrator.Dialogs
{
    public partial class FormArticleEdit : Form
    {
        private Multilang title = new Multilang("");
        private Multilang content = new Multilang("");
        private Article article;
        private bool updating = false;

        public FormArticleEdit()
        {
            InitializeComponent();

            Category.RefreshList();
            comboBoxCategory.Items.Add(new Category());
            comboBoxCategory.Items.AddRange(Category.AllCategories.OrderBy(x => x.Name).ToArray());

            comboBoxAuthor.Items.Add(new Author());
            comboBoxAuthor.Items.AddRange(Author.GetAll().OrderBy(x => x.Name).ToArray());

            var title_changed = Observable
                                .FromEvent<EventArgs>(textBoxTitle, "TextChanged");                                

            var text_changed = Observable
                                .FromEvent<EventArgs>(richTextBoxContent, "TextChanged")
                                .Merge(title_changed)
                                .Select(x => new {Lang=GetLang(), Title=textBoxTitle.Text, Content=richTextBoxContent.Rtf})
                                .Throttle(TimeSpan.FromMilliseconds(500))
                                .ObserveOnDispatcher();
            
            text_changed.Subscribe(
                x => ContentTextChanged(x.Lang, x.Title, x.Content)
                    );
        }

        public void SetArticle(Article article)
        {
            updating = true;
            try
            {
                this.article = article;

                if (article.Category != null)
                    comboBoxCategory.SelectedItem = article.Category;
                else
                    comboBoxCategory.SelectedIndex = -1;

                if (article.Author.IsNull())
                    comboBoxAuthor.SelectedIndex = -1;
                else
                    comboBoxAuthor.SelectedItem = comboBoxAuthor.Items.Cast<Author>().Where(x => x.Equals(article.Author)).First();

                long insd = article.InsertDate.Ticks;
                dateTimePicker1.Value = new DateTime(insd);
                dateTimePicker2.Value = new DateTime(insd);

                title.Value = article.Title;
                content.Value = article.Content;
                checkBoxPublish.Checked = article.Publish;
                buttonImages.Text = string.Format("Images ({0})", article.Images.Count());
                ApplyTextChanges();
            }
            finally
            {
                updating = false;
            }
        }

        public void ContentTextChanged(string lang, string title, string content)
        {
            if (!updating)
            {
                this.title[lang] = title;
                this.content[lang] = HttpUtility.HtmlEncode(content);
            }
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            
        }

        static public DialogResult Edit(Article article)
        {
            FormArticleEdit form = new FormArticleEdit();
            form.SetArticle(article);
            var result = form.ShowDialog();
            if (result == DialogResult.OK)
            {
                if (article.Id == -1)
                    article.Insert();
                else
                    // update article here
                    article.Update();
            }
            else
                article.Refresh();
            return result;
        }

        private void tabControlContent_SelectedIndexChanged(object sender, EventArgs e)
        {
            panelContent.Parent = tabControlContent.SelectedTab;
            // change text
            ApplyTextChanges();            
        }

        private string GetLang()
        {
            switch (tabControlContent.SelectedTab.Text[0])
            {
                case 'I':
                    return "ID";
                case 'E':
                    return "EN";
                case 'N':
                    return "NL";
            }
            return "";

        }

        private void ApplyTextChanges()
        {
            try
            {
                richTextBoxContent.Rtf = HttpUtility.HtmlDecode(content[GetLang()]);
            }
            catch
            {
                richTextBoxContent.Text = content[GetLang()];
            }
            textBoxTitle.Text = title[GetLang()];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            article.Title = title.Value;
            article.Content = content.Value;
        }

        private void buttonImages_Click(object sender, EventArgs e)
        {
            FormArticleImagesEdit.Execute(article);
            buttonImages.Text = string.Format("Images ({0})", article.Images.Count());
        }

        private void comboBoxAuthor_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!updating) 
                article.Author = (Author)comboBoxAuthor.SelectedItem;
        }

        private void comboBoxCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!updating)
                article.Category = (Category)comboBoxCategory.SelectedItem;
        }

        private void checkBoxPublish_CheckedChanged(object sender, EventArgs e)
        {
            if (!updating)
                article.Publish = checkBoxPublish.Checked;
        }

        private void dateTimePicker1_ValueChanged_2(object sender, EventArgs e)
        {
            if (!updating)
                article.InsertDate = new DateTime(dateTimePicker1.Value.Date.Ticks + dateTimePicker2.Value.TimeOfDay.Ticks);
        }

        private void StyleButtonClicked(object sender, EventArgs e)
        {
            FontStyle style = FontStyle.Regular;
            bool on;

            if (sender == buttonBold)
            {
                style = FontStyle.Bold;
                on = richTextBoxContent.SelectionFont.Bold;
            }
            if (sender == buttonItalic)
            {
                style = FontStyle.Italic;
                on = richTextBoxContent.SelectionFont.Italic;
            }
            if (sender == buttonUnderline)
            {
                style = FontStyle.Underline;
                on = richTextBoxContent.SelectionFont.Underline;
            }

            richTextBoxContent.SelectionFont =
                new Font(richTextBoxContent.SelectionFont, style);

        }

    }
}
